/*
 * Copyright 2005-2013 biz-united. All rights reserved.
 * Support: http://www.biz-united.com.cn
 * License: http://www.biz-united.com.cn/?page_id=5&act=3
 */
package com.home766.controller.pad;

import com.home766.service.SchemeService;
import net.biz.Message;
import net.biz.controller.shop.BaseController;
import net.biz.entity.*;
import net.biz.service.*;
import net.biz.util.JsonUtils;
import net.biz.util.ParamsUtil;
import net.biz.util.WebUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.InvocationTargetException;
import java.util.*;

/**
 * Controller - 购物车
 * 
 * @author BIZ Team
 * @version 3.0
 */
@Controller
@RequestMapping("/pad/cart")
public class PadCartController extends BaseController {

	@Resource(name = "memberServiceImpl")
	private MemberService memberService;
	@Resource(name = "productServiceImpl")
	private ProductService productService;
	@Resource(name = "cartServiceImpl")
	private CartService cartService;
	@Resource(name = "cartItemServiceImpl")
	private CartItemService cartItemService;

	@Resource(name="schemeServiceImpl")
	private SchemeService schemeService;
	@Resource(name = "logServiceImpl")
	private LogService logService;
	/**
	 * 添加
	 */
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public @ResponseBody
    Message add(Long id, Integer quantity, Integer cartType, HttpServletRequest request, HttpServletResponse response) {
		if (quantity == null || quantity < 1) {
			return ERROR_MESSAGE;
		}
//		if(!chekLogin(request)){
//			return Message.warn("shop.cart.cartLogin");
//		}
		if(null==cartType){
			return Message.warn("shop.cart.cartTypeExsit");
		}
		Product product=null;
		if(ParamsUtil.CART_TYPE_NORMAL==cartType){
			product = productService.find(id);
			if (product == null) {
				return Message.warn("shop.cart.productNotExsit");
			}
			if (!product.getIsMarketable()) {
				return Message.warn("shop.cart.productNotMarketable");
			}
			if (product.getIsGift()) {
				return Message.warn("shop.cart.notForSale");
			}
		}
		Cart cart = cartService.getCurrent();
		Member member = memberService.getCurrent();

		if (cart == null) {
			cart = new Cart();
			cart.setKey(UUID.randomUUID().toString() + DigestUtils.md5Hex(RandomStringUtils.randomAlphabetic(30)));
			cart.setMember(member);
			cartService.save(cart);
		}

		if (Cart.MAX_PRODUCT_COUNT != null && cart.getCartItems().size() >= Cart.MAX_PRODUCT_COUNT) {
			return Message.warn("shop.cart.addCountNotAllowed", Cart.MAX_PRODUCT_COUNT);
		}
		if (cart.contains(product)) {
			CartItem cartItem = cart.getCartItem(product);
			if (CartItem.MAX_QUANTITY != null && cartItem.getQuantity() + quantity > CartItem.MAX_QUANTITY) {
				return Message.warn("shop.cart.maxCartItemQuantity", CartItem.MAX_QUANTITY);
			}
			if (product.getStock() != null && cartItem.getQuantity() + quantity > product.getAvailableStock()) {
				return Message.warn("shop.cart.productLowStock");
			}
			cartItem.add(quantity);
			cartItemService.update(cartItem);
		} else {
			if (CartItem.MAX_QUANTITY != null && quantity > CartItem.MAX_QUANTITY) {
				return Message.warn("shop.cart.maxCartItemQuantity", CartItem.MAX_QUANTITY);
			}
			if(cartType== ParamsUtil.CART_TYPE_NORMAL){
				if (product.getStock() != null && quantity > product.getAvailableStock()) {
					return Message.warn("shop.cart.productLowStock");
				}
			}
			CartItem cartItem = new CartItem();
			cartItem.setQuantity(quantity);
			cartItem.setProduct(product);
			cartItem.setCartType(cartType);
			cartItem.setCart(cart);
			cartItemService.save(cartItem);
			cart.getCartItems().add(cartItem);
		}

		if (member == null) {
			WebUtils.addCookie(request, response, Cart.ID_COOKIE_NAME, cart.getId().toString(), Cart.TIMEOUT);
			WebUtils.addCookie(request, response, Cart.KEY_COOKIE_NAME, cart.getKey(), Cart.TIMEOUT);
		}
		return Message.success("shop.cart.addSuccess", cart.getQuantity(), currency(cart.getEffectivePrice(), true, false));
	}

	/**
	 * 列表
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list(ModelMap model) {
		model.addAttribute("cart", cartService.getCurrent());
		return "/pad/cart/cart";
	}
	/**
	 * head_bar cart message
	 */
	@ResponseBody
	@RequestMapping(value = "/headList", method = RequestMethod.GET,produces=("text/plain; charset=utf-8"))
	public String headList(HttpServletRequest request) {
		Map<String, Object> result=new HashMap<String, Object>();
		String operation="search";
		String content="head_bar cart message";
		try {
			result = cartService.getLoginHeadCart();
		} catch (IllegalAccessException e) {
			logStaff(operation, content, request);
		} catch (InvocationTargetException e) {
			logStaff(operation, content, request);
		} catch (NoSuchMethodException e) {
			logStaff(operation, content, request);
		}
		String str= JsonUtils.toJson(result);
		return str;
	}

	/**
	 * 编辑
	 */
	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	public @ResponseBody
    Map<String, Object> edit(Long id, Integer quantity, HttpServletRequest request) {
		Map<String, Object> data = new HashMap<String, Object>();
		if (quantity == null || quantity < 1) {
			data.put("message", ERROR_MESSAGE);
			return data;
		}
//		if(!chekLogin(request)){
//			 data.put("message", Message.error("shop.cart.cartLogin"));
//			 return data;
//		}
		Cart cart = cartService.getCurrent();
		if (cart == null || cart.isEmpty()) {
			data.put("message", Message.error("shop.cart.notEmpty"));
			return data;
		}
		CartItem cartItem = cartItemService.find(id);
		Set<CartItem> cartItems = cart.getCartItems();
		if (cartItem == null || cartItems == null || !cartItems.contains(cartItem)) {
			data.put("message", Message.error("shop.cart.cartItemNotExsit"));
			return data;
		}
		if (CartItem.MAX_QUANTITY != null && quantity > CartItem.MAX_QUANTITY) {
			data.put("message", Message.warn("shop.cart.maxCartItemQuantity", CartItem.MAX_QUANTITY));
			return data;
		}
		Product product = cartItem.getProduct();
		if (product.getStock() != null && quantity > product.getAvailableStock()) {
			data.put("message", Message.warn("shop.cart.productLowStock"));
			return data;
		}
		cartItem.setQuantity(quantity);
		cartItemService.update(cartItem);

		data.put("message", SUCCESS_MESSAGE);
		data.put("subtotal", cartItem.getSubtotal());
		data.put("isLowStock", cartItem.getIsLowStock());
		data.put("quantity", cart.getQuantity());
		data.put("effectivePoint", cart.getEffectivePoint());
		data.put("effectivePrice", cart.getEffectivePrice());
		data.put("promotions", cart.getPromotions());
		data.put("giftItems", cart.getGiftItems());
		return data;
	}

	/**
	 * 删除
	 */
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public @ResponseBody
    String delete(Long id, HttpServletRequest request) {
		Map<String, Object> data = new HashMap<String, Object>();
//		if(!chekLogin(request)){
//			 data.put("message", Message.error("shop.cart.cartLogin"));
//			 return data;
//		}
		Cart cart = cartService.getCurrent();
		if (cart == null || cart.isEmpty()) {
			data.put("message", Message.error("shop.cart.notEmpty"));
			String str= JsonUtils.toJson(data);
			return str;
		}
		CartItem cartItem = cartItemService.find(id);
		Set<CartItem> cartItems = cart.getCartItems();
		if (cartItem == null || cartItems == null || !cartItems.contains(cartItem)) {
			data.put("message", Message.error("shop.cart.cartItemNotExsit"));
			String str= JsonUtils.toJson(data);
			return str;
		}
		cartItems.remove(cartItem);
		cartItemService.delete(cartItem);

		data.put("message", SUCCESS_MESSAGE);
		data.put("quantity", cart.getQuantity());
		data.put("effectivePoint", cart.getEffectivePoint());
		data.put("effectivePrice", cart.getEffectivePrice());
		data.put("promotions", cart.getPromotions());
		data.put("isLowStock", cart.getIsLowStock());
		String str= JsonUtils.toJson(data);
		return str;
	}

	/**
	 * 清空
	 */
	@RequestMapping(value = "/clear", method = RequestMethod.POST)
	public @ResponseBody
    Message clear() {
		Cart cart = cartService.getCurrent();
		cartService.delete(cart);
		return SUCCESS_MESSAGE;
	}

	@ResponseBody
	@RequestMapping(value="/check",method=RequestMethod.GET,produces=("text/plain; charset=utf-8"))
	public String checkCartItem(Long[] ids){
		Integer checkParams=null;
		if(null!=ids&&ids.length>0){
			Cart cart=cartService.getCurrent();
			Member member=getCurrent();
			if(null!=member&&member.getIsEnabled()&&!member.getIsLocked()){
				cartService.updateCart(member.getCart().getId());
			}
			Set<CartItem> set= cart.getCartItems();
			List<CartItem> list=new ArrayList<CartItem>();
			for(Long id:ids){
				for(CartItem ci:set){
					if(id.longValue()==ci.getId().longValue()){
						if(checkParams==null){
							checkParams=ci.getCartType();
						}
						if(checkParams!=ci.getCartType()){
							String str= JsonUtils.toJson(Message.warn("shop.cart.submitCartTypeNot"));
							return str;
						}else{
							list.add(ci);
						}
					}
				}
			}
			if(ids.length==list.size()){
				for(CartItem ci:list){
					ci.setIsSubmit(true);
					cartItemService.update(ci);
				}
			}else{
				String str= JsonUtils.toJson(Message.warn("shop.cart.submitCartTypeNot"));
				return str;
			}
		}else{
			String str= JsonUtils.toJson(Message.warn("shop.cart.isSubmitIdEmpty"));
			return str;
		}
		String str= JsonUtils.toJson(Message.success("shop.message.success"));
		return str;
	}
	private void logStaff(String operation, String content, HttpServletRequest request){
		Log log=new Log();
		log.setOperation(operation);
		log.setContent(content);
		log.setIp(request.getRemoteAddr());
		logService.save(log);
	}
	private boolean chekLogin(HttpServletRequest request){
		HttpSession session=request.getSession();
		Object obj=session.getAttribute(Member.PRINCIPAL_ATTRIBUTE_NAME);
		if(obj==null){
			return false;
		}
		return true;
	}
}